package com.kit.data.kitopeso.analysis.libs

import android.app.Application
import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import com.google.gson.Gson
import com.kit.data.kitopeso.KitoApp
import com.kit.data.kitopeso.PathMaping
import com.kit.data.kitopeso.base.BaseParams
import com.kit.data.kitopeso.net.U
import com.kit.data.kitopeso.tools.LogUtil
import com.kit.data.kitopeso.tools.SpUtils

object ReferrerLib {

    private var _ref: String = ""

    private var _client: InstallReferrerClient? = null

    fun fetch(context: Application, onSuccess: (String) -> Unit) {
        try {
            if (_ref.isBlank()) {
                _client = InstallReferrerClient.newBuilder(context).build()
                _client?.let {
                    it.startConnection(object :
                        InstallReferrerStateListener {
                        override fun onInstallReferrerSetupFinished(responseCode: Int) {
                            when (responseCode) {
                                InstallReferrerClient.InstallReferrerResponse.OK -> {
                                    try {
                                        _ref = it.installReferrer?.installReferrer ?: ""
                                        it.endConnection()

                                        //
                                        onSuccess.invoke(referrerParams())

                                    } catch (e: Exception) {
                                        e.printStackTrace()
                                    }
                                }

                                InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED -> {
                                    println("FEATURE_NOT_SUPPORTED")
                                }

                                InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE -> {
                                    println("SERVICE_UNAVAILABLE")
                                }
                            }
                        }

                        override fun onInstallReferrerServiceDisconnected() {
                        }
                    })
                }
            } else {
                onSuccess.invoke(referrerParams())
            }
        } catch (e: Exception) {
            //
        }
    }

    fun referrer(): String {
//        return "gclidxxxxxx"
        return _ref
    }

    fun referrerParams(): String {
        val token = SpUtils.get_string(KitoApp.getInstance(), SpUtils.KEY_TOKEN, "")
        val data = hashMapOf(
            "product" to U.URL_MAIN_PRODUCT, // TODO: 补充产品名
            "path" to PathMaping.PathList[27], // TODO: 补充映射
            "token" to token, // TODO: 补充token
            "channelCode" to referrer(),
            "subChannelCode" to referrer(),
            "androidId" to AdIdLib.androidId(),
            "advertId" to AdIdLib.adId(),
            "isLimitAdTrackingEnabled" to AdIdLib.adEnabled().toString(),
            "aduid" to AdIdLib.adId(),
            "aduidPath" to AdIdLib.androidId(),
            "version" to BaseParams.getVersion(KitoApp.getInstance()),
            "apiVersion" to "v3"
        )

        LogUtil.e("me", "ReferrerLib data->$data")

        return Gson().toJson(data).trim()
    }
}